<template>
  <!-- 在线咨询 访客报表-->
  <div class="sourcePage" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time
              type="other"
              :query="query"
              @isFold="isShowFold"
              :otherShow="false"
            ></date-time>
            <el-button
              type="primary"
              class="primary_btn fr find"
              v-on:click.stop="search(1)"
              >{{ $t("public.search2") }}</el-button
            >
            <div class="clear"></div>
          </div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{ $t("report.imAccessId") }}：</span>
                  <el-select
                    size="mini"
                    v-model.trim="selectedAccessIdList"
                    multiple
                    filterable
                    :placeholder="$t('report.searchByName')"
                  >
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
    </div>
    <div :id="id">
      <div class="tab">
        <div class="export">
          <el-button
            class="primary_btn fr formal"
            @click="$refs.formulaEditorDialog.open()"
          >
            {{ $t("report.formalTitle") }}</el-button
          >
          <el-button
            class="primary_btn fr set_header"
            v-on:click.stop="config"
            >{{ $t("report.setHeaderConfig") }}</el-button
          >

          <el-button
            class="primary_btn fr report_excel_btn"
            @click.stop="exportExcel"
            >{{ $t("report.exportXls") }}</el-button
          >

          <el-button class="primary_btn fr pdf report_excel_btn" @click.stop="exportPdf">{{
            $t("report.exportPDF")
          }}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{
                  $t("report.toggleInstructe")
                }}</span>
              </template>
              <div>
                1. {{ $t("report.views") }}<br />
                2. {{ $t("report.traffic") }}<br />
                3. {{ $t("report.ipNum") }}<br />
                4. {{ $t("report.visitorsConsultingNum") }}<br />
                5. {{ $t("report.consultingNumber") }}<br />
                <p class="custom_alg">{{ $t("report.ziDingYi") }}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{ index + 6 }}.{{ item.formulaInstr }}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table
          :data="tableData"
          :config="[...headOptions.Config, ...formulasConfig]"
          :sum="totalData"
        >
        </report-table>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      top="10%"
      :title="$t('report.reportExportHelp')"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>{{ $t("report.reportExportTipTitle") }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{
          $t("public.cancel")
        }}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirm">{{
          $t("public.confirm")
        }}</el-button>
      </span>
    </el-dialog>
    <header-option
      v-show="isShow"
      :show="isShow"
      :option="headOptionsShow"
      type="im_report_flow_date"
      v-on:close="close"
      :headCustom="formulasConfig"
    ></header-option>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog
      ref="formulaEditorDialog"
      :headOptionsConfig="headOptions.Config"
      @closeFormulaDialog="closeFormulaDialog"
      reportName="呼入时间趋势报表"
      :reportType="id"
    />
  </div>
</template>
<script>
import affix from "../../../../ui-modules/affix/Affix.vue";
import unfold from "../../../../ui-modules/unfold/index.vue";
import dateTime from "../../base/datetime.vue";
import exportCountDown from "../../base/exportCountDown.vue";
import reportTable from "../../base/reportTable.vue";
import FormulaEditorDialog from "../../base/FormulaEditorDialog.vue";
import headerOption from "../../base/headerOption.vue";
import { deepClone, optionTimeTypeCheck, isHasFunc } from "@/utils/m7Utils.js";
import {
  exportReportPdf,
  headOptionsToXlsxHeaders,
  searchTime,
  checkTime,
  exportNum,
  mixData
} from "@/utils/reportUtils.js";
import Pagination from "@/components/public-modules/card/Pagination";
import * as XlsxUtil from "src/utils/XlsxUtil.umd.js";

export default {
  name: "im_report_flow_date",
  data() {
    return {
      lookparam: "page",
      isLookFull: true,
      isFullUrl: false,
      positiveSessionCount: false, // 产生对话数的数据
      isFold: false, // 是否展示搜索条件
      selectedAccessIdList: [], // 接入号绑定值
      accessIdOptions: [], // 接入号渲染数据
      id: "im_report_flow_date", // 查询id
      title: this.$t("report.imReportFlow"),
      query: {}, // 查询条件
      dialogVisible: false, // 导出pdf弹窗开关
      loading: false, // 查询时展示加载的开关
      headOptions: { Config: [], data: [] }, // 表头数据
      serverData: [], // 原始查询table数据
      paginationRecord: {
        // 翻页组件传入的数据
        currentPage: 1,
        small: "small",
        num: 20,
      },
      countRecord: 0, // 当前页
      totalPageRecord: 1, // 共有多少页
      countNum: 0, // 共有多少条记录
      headOptionsShow: {}, // 配置表头需传参数
      isShow: false, // 配置表头弹层开关
      formulas: [], // 公式数据
    };
  },
  components: {
    affix,
    unfold,
    dateTime,
    reportTable,
    Pagination,
    exportCountDown,
    FormulaEditorDialog,
    headerOption,
  },
  watch: {
    // 监测自定义公式变化 更新数据
    formulas (cur, old) {
      if (this.isSearch) {
        return
      }
      if (!this.serverData || this.serverData.length === 0) {
        return
      }
      this.serverData = deepClone(mixData(this.serverData, this.formulas))
    }
  },
  computed: {
    // 处理table数据
    tableData() {
      return this.getTableData(this.serverData);
    },
    // 计算table合计
    totalData() {
      return this.getTotalData(this.serverData, this.headOptions);
    },
    configHeaderBool() {
      return this.$store.state.report.setConfigHeaderBool;
    },
    // 自定义表头
    formulasConfig() {
      return this.formulas.map((d, i) => {
        return {
          displayname: d.displayname,
          name: d.name,
          order: d.order,
          show: d.show,
          timeType: "none",
          digits: d.digits,
          type: d.type,
        };
      });
    },
  },
  methods: {
    // 查看页面切换执行
    turnSearch(str) {
      this.isLookFull = !this.isLookFull;
      this.lookparam = str;
      this.search(1);
    },
    // 处理table数据
    getTableData(serverData) {
      if (!serverData || serverData.length === 0) {
        return [];
      }

      let data = deepClone(serverData);

      data.forEach((item) => {
        item.time = item._id;
      });

      return data;
    },
    // 计算table合计
    getTotalData(serverData, headOptions) {
      if (!serverData || serverData.length === 0) {
        return [{ time: this.$t("report.total") }];
      }
      let headerConfig = headOptions.Config || [];
      let datas = serverData;
      let total = {
        time: this.$t("report.total"),
      };

      for (let i = 0; i < headerConfig.length; i++) {
        if (headerConfig[i].name === "time") {
          continue;
        }
        for (let j = 0; j < datas.length; j++) {
          if (!isNaN(datas[j][headerConfig[i].name])) {
            if ((headerConfig[i].name in total) === false) {
              total[headerConfig[i].name] = 0
            }
            total[headerConfig[i].name] += datas[j][headerConfig[i].name]
          }
        }
      }
      total = mixData([total], this.formulas)[0]
      return [total]
    },
    // 是否展开收起查询条件
    isShowFold(bool) {
      this.isFold = bool;
    },
    // 查询数据的条件
    getSearchQueryData(page, limit, isExport) {
      let data = {
        reportType: this.id,
        account: this.$store.state.session.user.account,
        query: { reportType: this.id },
        page: page || 1,
        limit: limit,
      };
      if (!isExport) {
        this.paginationRecord.currentPage = page;
      }
      let query = deepClone(this.query);
      if (query.timeType === "other") {
        // 校验类型与时间
        let message = checkTime(query.StartTime, query.EndTime, false, true);
        if (message !== true) {
          this.$message.error(this.$t(message));
          return;
        }
      }
      if (this.selectedAccessIdList.length > 0) {
        query.selectedAccessIdList = this.selectedAccessIdList.join(',')
      }
      data.query.urlType = this.lookparam;
      data.query = Object.assign({}, data.query, query);
      return data;
    },
    // 查询方法
    search(page) {
      var queryData = this.getSearchQueryData(page, 20);

      if (!queryData) {
        return;
      }

      this.loading = true;
      this.$store.dispatch("queryImFlowReport", queryData).then((res) => {
          // 表头
          this.headOptions = optionTimeTypeCheck(
            deepClone(res.tableHeader) || this.headOptions
          );
          this.serverData = deepClone(res.data) || this.serverData;
          this.page = queryData.page;
          let count = res.count || 0;
          if (count) {
            this.countNum = count;
            this.totalPageRecord = Math.ceil(count / 20);
            this.countRecord = count / 2;
          } else {
            this.countNum = 0;
            this.totalPageRecord = 1;
            this.countRecord = 1;
          }
          this.isFullUrl = res.isFullUrl;

          if (!page || page === 1) {
            let data = deepClone(this.serverData);
            data = data.slice(0, 10);
          }
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
            if (resp.success) {
              this.formulas = resp.data.Formulas
              this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
              this.serverData = deepClone(mixData(res.data, this.formulas)) || deepClone(this.serverData)
              this.noDealDate = deepClone(mixData(res.data, this.formulas))
              this.loading = false
            }
          })
        });
    },
    // 导出表格数据执行的方法(前端)
    exportExcel() {
      var queryData = this.getSearchQueryData(1, exportNum.searchNum, true);

      if (!queryData) {
        return;
      }
      if (this.countNum > exportNum.maxExportNum) {
        this.$message.warning(this.$t("report.imReportMoreDateTipErro"));
        return;
      }
      this.loading = true;
      this.$store
        .dispatch("queryImFlowReport", queryData)
        .then((res) => {
          this.loading = false;
          if (res.count > exportNum.maxExportNum) {
            this.$message.warning(this.$t("report.imReportMoreDateTipErro"));
            return;
          }
          this.exportXlsx(res);
        });
    },
    // 导出表格数据执行的方法(前端)
    exportXlsx(res) {
      var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || []);
      var serverData = deepClone(mixData(res.data, this.formulas)) || [];
      

      var tableData = this.getTableData(serverData, headOptions).map((d) => {
        var reg = /<\/?.+?\/?>/g;
        d.time = d.time.replace(reg, "");
        return d;
      });
      var headers = headOptionsToXlsxHeaders([...headOptions.Config,...this.formulasConfig]);
      if (tableData && tableData.length) {
        var sum = this.getTotalData(serverData, headOptions);
        tableData = tableData.concat(sum);
      }

      var dh = XlsxUtil.getDownloadHelper(headers, tableData);
      var timeStamp = XlsxUtil.dateFormat(new Date(), "yyyy-MM-dd hh-mm-ss");
      dh.download(this.$t("report.imReportFlow") + timeStamp);
    },
    // 翻页查询方法 参数当前请求页数
    turnPageRecord(pageNum) {
      this.paginationRecord.currentPage = pageNum;
      this.search(pageNum);
    },
    // 导出PDF
    exportPdf() {
      this.dialogVisible = true;
    },
    // 确认导出pdf执行的方法
    confirm() {
      this.dialogVisible = false;
      exportReportPdf({
        title: this.$t("report.imReportFlow") + searchTime(this.query),
        id: this.id,
      });
    },
    // 自定义公式弹窗关闭外抛事件
    closeFormulaDialog() {
      this.isSearch = false;
      this.$store
        .dispatch("queryFetchFormula", { type: this.id })
        .then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
            this.serverData = deepClone(mixData(this.serverData, this.formulas))
            this.tableData = this.getTableData(this.serverData, this.groupName)
          }
        });
    },
    // 获取表头数据
    config() {
      this.$store
        .dispatch("getReportTableHeader", "im_report_flow_date")
        .then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res);
          this.isShow = !this.isShow;
        });
    },
    // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
    close(data) {
      this.isShow = false;
      if (data === "save") {
        this.search();
      }
    },
  },
  beforeMount() {
    this.$store
      .dispatch("getCache", { type: "accessIds" })
      .then((accessIds) => {
        this.accessIdOptions = accessIds.map((accessId) => ({
          label: `${accessId.name}[${accessId.platform}]`,
          name: accessId.name,
          platform: accessId.platform,
          value: accessId._id,
        }));
      });
    if (
      isHasFunc("func_forbid_config_formula", this.$store.state.session.user)
    ) {
      this.configFormula = false; // 没有自定义公式的配置权限
    }
    this.$nextTick(() => {
      this.search();
    });
  }
};
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .sourcePage
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .access1
        margin-right 30px
      .el-select
      .el-input
        width 600px
    .tab
      margin-top 0
      .deploy
        .tip
          margin-left 0
        .search-pagination
          float right
          line-height 23px
        .tex
          display inline-block
          margin 2px 10px 0 0
          height 26px
          line-height 26px
        .tex:hover
          color $cf-gray1
    .pank
      width 100%
      padding 20px
      margin-left 20px
      tr
        td
          line-height 24px
          &:nth-child(1)
            width 10%
          &:nth-child(2)
            width 50%
          &:nth-child(3)
            width 40%
      .line
        display inline-block
        margin-bottom 4px
        height 5px
      .number
        display inline-block
        width 60px
    .formal
      margin-left 10px
</style>
